<?php
$categoryGroups = $this->categoryGroups;
$firstCategoryCode = $categoryGroups->current()->group_code;
?>

<div class="ad_title_ctn">
    <h2>Quản lý nhóm (category)</h2>
</div>

<div class="ad_content_ctn">

    <div class="categories_ctn">

        <ul id="panelbar">
            <?php
            foreach ($categoryGroups as $aGroup) {
                echo ' <li id="panel_item'.$aGroup->group_code.'">
                <span class="title">Nhóm '.$aGroup->name.'</span>
                <input class="txtHiddenGroupCode" type="hidden" value="'.$aGroup->group_code.'">
                <div style="padding: 10px">
                    <div class="category_ctrl_ctn" >
                        <a id="btnAddCategory_'.$aGroup->id.'" class="k-button k-button-icontext k-grid-edit">
                            Thêm mới
                        </a>&nbsp;&nbsp;
                        <a id="btnDeleteCategory_'.$aGroup->id.'" class="k-button k-button-icontext k-grid-edit" >
                            Xóa
                        </a>&nbsp;&nbsp;
                        <a id="btnEditCategory_'.$aGroup->id.'" class="k-button k-button-icontext k-grid-edit" >
                            Sửa
                        </a>&nbsp;&nbsp;
                        <a id="btnUpCategory_'.$aGroup->id.'" style="display: none" class="k-button k-button-icontext k-grid-edit" >
                            Up
                        </a>&nbsp;&nbsp;
                        <a id="btnDownCategory_'.$aGroup->id.'" style="display: none" class="k-button k-button-icontext k-grid-edit">
                            Down
                        </a>
                    </div>
                    <div class="category_tree_ctn" id="category_tree_ctn_'.$aGroup->group_code.'">

                    </div>
                </div>
            </li>';
            }

            ?>

        </ul>
    </div>
</div>
<div id="wndAddCategory"></div>
<script type="text/x-kendo-template" id="addCategoryTemplate">
    <div id="add-category-container">
        <dl>
            <dt style="padding: 5px">
            <div> Nhóm cha : #= parent_name #
                <input  id='txtParentId'  name="txtParentId" type="hidden"    value='#= parent_id #'>
            </div>
            </dt>
            <dt style="padding: 5px"><div style="width: 70px; float:left"> Mã(*):</div>
            <input  id='txtCategoryId'  name="txtCategoryId" type="hidden"    value='#= id #'>
            <input  id='txtCategoryCode'  name="txtCategoryCode" class="k-textbox"  required  value='#= code #'>

            </dt>
            <dt style="padding: 5px"><div style="width: 70px;float:left"> Tên(*):</div>
            <input  style="width:400px" class="k-textbox"  required  id='txtCategoryName' value='#= name #'>


            </dt>
            <dt style="padding: 5px"><div style="width: 70px; float:left"> Mô tả:</div>
            <input style="width:400px"  class="k-textbox"  required  id='txtCategoryDescription' value='#= description #'>

            </dt>
            <dt style="padding: 5px">
                <span style="color:red" id="spnStatus"></span>
            </dt>
        </dl>
        <div style="padding: 10px 0px" >
            <a id="btnSaveMyCategory" class="k-button k-button-icontext k-grid-update" >
                <span class="k-icon k-update"></span>
                Lưu
            </a>
            <a id="btnCloseMyCategory" class="k-button k-button-icontext k-grid-cancel">
                <span class="k-icon k-cancel"></span>
                Cancel
            </a>
        </div>
    </div>
</script>

<script type="text/javascript">

var firstGroupCode = "<?php echo $firstCategoryCode?>";
$(document).ready(function() {
    $("#panelbar").kendoPanelBar({
        expandMode: "single",
        select: onSelectAGroup
    });

    function onSelectAGroup(e){
        groupCode = $(e.item).find("input.txtHiddenGroupCode").val();
        loadACategoryGroup(groupCode);


    }


    function loadACategoryGroup(groupCode){
//        groupCode=  firstGroupCode;
        contentContainer =$('#category_tree_ctn_'+groupCode);
        $(".category_tree_ctn").each(function(){
            $(this).html('');
            $(this).removeClass('k-widget k-treeview');
        })

        $.post('<?php echo '/admin/catalog/get-category-group-content'  ?>',
                {groupCode:groupCode}
                ,function(result){
                    contentContainer.html(result);
                    panelBar = $("#panelbar").data("kendoPanelBar");
                    panelBar.expand('#panel_item'+groupCode);
                });
    }

    if(firstGroupCode){
        loadACategoryGroup(firstGroupCode);


    }



    $('[id^=btnAddCategory]').click(function(){
        selectedNode = getTreeSelectedNode(treeview)
        data = treeview.dataItem(selectedNode);
        doAdd(data)

    });


    $('[id^=btnEditCategory]').click(function(){
        selectedNode = getTreeSelectedNode(treeview)
        data = treeview.dataItem(selectedNode);
        editCategory(data)

    });

    $('[id^=btnDeleteCategory]').click(function(){
        selectedNode = getTreeSelectedNode(treeview)
        data = treeview.dataItem(selectedNode);
        r=confirm("Bạn có chắc chắn xóa nhóm: "+ data.name )
        if (r==true)
        {
            deleteCategory(data,treeview)
        }


    });
    $('[id^=btnUpCategory]').click(function(){
        selectedNode = getTreeSelectedNode(treeview)
        data = treeview.dataItem(selectedNode);
        upCategory(data,treeview)

    });
    $('[id^=btnDownCategory]').click(function(){
        selectedNode = getTreeSelectedNode(treeview)
        data = treeview.dataItem(selectedNode);
        downCategory(data,treeview)
    });


    function getParent(categoryNode, treeview){
        parentNode = treeview.parent(categoryNode)
        if (parentNode.length == 0) {
            treeview.select(".k-item:first");
            parentNode = treeview.select();
        }
        return parentNode;
    }

    function doAdd(data){
        wndAddCategory.content(addCategoryTemplate({"parent_id":data.id,"parent_name":data.text,
            "id":'',"code":'',"name":'',"description":""}));
        wndAddCategory.center().open();
    }



    var addCategoryTemplate = kendo.template($("#addCategoryTemplate").html());
    var wndAddCategory = $("#wndAddCategory")
            .kendoWindow({
                title: "Thêm category",
                modal: true,
                visible: false,
                resizable: false,
                width: 500,
                activate: onActivateAddCategory

            }).data("kendoWindow");
    $("#wndAddCategory").keypress(function(event){
        //if the key press is ESC
        if (event.keyCode === 27) {
            //close the KendoUI window
            $("#wndAddCategory").data("kendoWindow").close();
        }

        if(event.keyCode === 13) {
            saveCategory(treeview);
        }
    });

    function onActivateAddCategory(){
        $("#txtCategoryCode").focus();
        $('#btnSaveMyCategory').click(function(){
            saveCategory(treeview);
        });

        $('#btnCloseMyCategory').click(function(){
            closeCategoryWindow();
        });




    }


    function closeCategoryWindow(){
        wndAddCategory.close();
    }

    function saveCategory(treeview){
        if(!validateCategorySave())
            return;
        id = $("#txtCategoryId").val();
        name = $("#txtCategoryName").val();
        code = $("#txtCategoryCode").val();
        description = $("#txtCategoryDescription").val();
        parentId = $("#txtParentId").val();


        $.post('<?php echo '/admin/catalog/save-category'  ?>',
                {name:name,code:code,description:description, id:id,parentId:parentId}
                ,function(result){
                    if (result.success){
                        closeCategoryWindow();
                        $("#spnStatus").html('');
                        selectedNode = getTreeSelectedNode(treeview);
                        categoryId = result.id;
                        if(!id)
                            treeview.append({id:categoryId,
                                name : name,
                                code : code,
                                description : description,
                                text: name
                            }, selectedNode);
                        else{

                            dataItem = treeview.dataItem(selectedNode);
                            dataItem.code = code;
                            dataItem.description = description;
                            dataItem.name = name;
                            dataItem.text = name;
                            dataItem.trigger("change", { action: "itemchange", field: "text" });
                        }
                        $('#error_ctn').addClass('blue_text').html('Cập nhật thành công');
                    }else{
                        $("#spnStatus").html(result.msg);
                    }
                },'json');
    }



    function validateCategorySave(){
        if(!$("#txtCategoryCode").val()){
            $("#spnStatus").html('Vui lòng nhập mã.');
            $("#txtCategoryCode").focus();
            return false;
        }

        if(!$("#txtCategoryName").val()){
            $("#spnStatus").html('Vui lòng nhập tên.');
            $("#txtCategoryName").focus();
            return false;
        }


        return true;
    }
    function editCategory(data){
        wndAddCategory.content(addCategoryTemplate({"id":data.id, "parent_id":'',"parent_name":'',
            "code":data.code,"name":data.text,"description":data.description}));
        wndAddCategory.title("Sửa category "+ data.text)
        wndAddCategory.center().open();
    }

    function deleteCategory(data,treeview){
        $.post('<?php echo '/admin/catalog/remove-category'  ?>',
                {id:data.id}
                ,function(result){
                    if (result.success){
                        selectedNode = getTreeSelectedNode(treeview)
                        treeview.remove(selectedNode);
                        $('[id^=btnUpCategory]').hide();
                        $('[id^=btnDownCategory]').hide();
                        $('#error_ctn').addClass('blue_text').html('Xóa nhóm: <b>'+ data.name + '</b> thành công');

                    }else{
                        $('#error_ctn').removeClass('blue_text').html(result.msg);
                        alert(result.msg);
                    }
                },'json');

    }

    function upCategory(data,treeview){
        $.post('<?php echo '/admin/catalog/up-category'  ?>',
                {id:data.id}
                ,function(result){
                    if (result.success){
                        $.post('<?php echo '/admin/catalog/category-list'  ?>',
                                {id:data.id}
                                ,function(result){

                                    categoryAsKendoDataSourceJson = result;
                                    treeview.setDataSource(categoryAsKendoDataSourceJson);
                                    treeview.expand(".k-item");
                                    selectedItem = treeview.findByText(data.text);
                                    treeview.select(selectedItem);
                                },'json');
                    }else{
                        $('#error_ctn').removeClass('blue_text').html(result.msg);
                        alert(result.msg);
                    }
                },'json');

    }

    function downCategory(data,treeview){
        $.post('<?php echo '/admin/catalog/down-category'  ?>',
                {id:data.id}
                ,function(result){
                    if (result.success){
                        $.post('<?php echo '/admin/catalog/category-list'  ?>',
                                {id:data.id}
                                ,function(result){

                                    categoryAsKendoDataSourceJson = result;
                                    treeview.setDataSource(categoryAsKendoDataSourceJson);
                                    treeview.expand(".k-item");
                                    selectedItem = treeview.findByText(data.text);
                                    treeview.select(selectedItem);
                                },'json');
                    }else{
                        $('#error_ctn').removeClass('blue_text').html(result.msg);
                        alert(result.msg);
                    }
                },'json');
    }
});

</script>